/*
 * HourTimer.cpp
 *
 *  Created on: 2020年1月11日
 *      Author: terry
 */

#include "HourTimer.h"
#include "DateTime.h"
#include <algorithm>
#include "CLog.h"


const int HourTimer::DEF_INTERVAL = 10 * 1000;


HourTimer::HourTimer():
	m_handler()
{
}

HourTimer::~HourTimer()
{
	close();
}

void HourTimer::setHandler(TimerHandler handler)
{
	m_handler = handler;
}

bool HourTimer::open()
{
	if (isOpen())
	{
		close();
	}

	bool got = start();

	setName("HourTimer");
	
	return got;
}

void HourTimer::close()
{
	if (isRunning())
	{
		stop();
	}
}

bool HourTimer::isOpen()
{
	return isRunning();
}

void HourTimer::resetTime()
{
	m_event.post();
}

int HourTimer::run()
{
	while (!m_canExit)
	{
		int interval = checkTime();
		m_event.timedwait(interval);
	}
	return 0;
}

void HourTimer::doStop()
{
	m_event.post();
}

int64_t HourTimer::getClock()
{
	return comn::DateTime::getTime();
}

int HourTimer::checkTime()
{
	int ms = DEF_INTERVAL;

	int64_t clock = getClock();
	comn::DateTime dt = comn::DateTime::now();
	if (dt.getSecond() <= 1)
	{
		int minute = dt.getMinute();
		if (minute == 0)
		{
			fireHour(dt.totalSecond(), dt.getWeekday(), dt.getHour());
		}
		else if (minute == 59)
		{
			ms = 60 * 1000 - (dt.getSecond() * 1000 + dt.getMillisecond());
			ms = std::min(ms, DEF_INTERVAL);
		}
	}
	else
	{
		ms = 60 * 1000 - (dt.getSecond() * 1000 + dt.getMillisecond());
		ms = std::min(ms, DEF_INTERVAL);
	}

    //CLog::debug("checkTime. ms: %d\n", ms);

	return ms;
}

void HourTimer::fireHour(int64_t clock, int weekday, int hour)
{
	if (m_handler)
	{
		m_handler(clock, weekday, hour);
	}
}
